package com.bookstore.filter;

import com.bookstore.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(urlPatterns = {"/admin/index.jsp", "/admin/products_list.jsp", "/admin/user_list.html", "/admin/product.do"})
public class AdminFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1.先对方法参数进行强转
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //2.判断当前是否有登录信息，以及登录的用户权限是否足够
        //2.1 获取 Session 对象
        HttpSession session = request.getSession();
        //2.2 从 session 当中拿 attribute user
        User user = (User) session.getAttribute("user");
        if (user == null || user.getRole() != 1) {
            response.sendRedirect("./login.html");
        } else {
            //允许请求往下走
            filterChain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {

    }
}
